package com.ask.forMe.service.impl;

import com.ask.forMe.model.entity.Rating;
import com.ask.forMe.mapper.RatingMapper;
import com.ask.forMe.service.RatingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RatingServiceImpl extends ServiceImpl<RatingMapper, Rating> implements RatingService {
    @Autowired
    private RatingMapper ratingMapper;

    /**
     * 构建用户-商品评分矩阵
     *
     * @return
     */
    @Override
    public Map<Long, Map<Long, Double>> getItemUserRatings() {
        // 1. 查询Rating表的所有数据(user_id, item_id, rating, time)
        List<Rating> ratings = list();
        Map<Long, Map<Long, Double>> itemUserRatings = new HashMap<>();

        // 2. 构建用户评分矩阵，key为商品id, value为用户对该商品的评分Map<userId, rating>
        for (Rating rating : ratings) {
            itemUserRatings
                    .computeIfAbsent(rating.getItemId(), k -> new HashMap<>())
                    .put(rating.getUserId(), rating.getRating());
        }
        return itemUserRatings;
    }

    /**
     * 查询用户对于某个商品的综合评分
     *
     * @param userId
     * @param itemId
     * @return
     */
    @Override
    public Rating getByUserItemId(Long userId, Long itemId) {
        QueryWrapper<Rating> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("item_id", itemId);
        Rating rating = ratingMapper.selectOne(queryWrapper);
        return rating;
    }

    /**
     * 跟新用户对于某个商品的综合评分
     *
     * @param userId
     * @param itemId
     */
    @Override
    public boolean updateByUserItemId(Long userId, Long itemId, Double rating) {
        UpdateWrapper<Rating> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId).eq("item_id", itemId);

        Rating updateData = new Rating();
        updateData.setRating(rating);
        updateData.setUpdateTime(LocalDateTime.now());

        int success = ratingMapper.update(updateData, updateWrapper);
        return success > 0;
    }
}
